package com.qing.config.security.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qing.config.security.mapper.UsersMapper;
import com.qing.config.security.pojo.JwtUser;
import com.qing.config.security.pojo.Users;
import com.qing.config.security.utils.FaceUtil;
import com.qing.config.security.utils.JwtTokenUtil;
import com.qing.config.security.utils.MyPasswordEncoder;
import com.qing.pojo.Employee;
import com.qing.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author qinghua
 * @date 2022/5/31 16:12
 */
@RestController
@RequestMapping("/securityUser")
public class UsersController {

    @Autowired
    private FaceUtil faceUtil;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private MyPasswordEncoder myPasswordEncoder;

    @PostMapping("/faceLogin")
    public void faceLogin(@RequestParam("image") String str, HttpServletResponse httpServletResponse) throws IOException {

        String res = faceUtil.searchFace(str, "csi_home");

        if ((JSONObject.parseObject(res).getString("error_msg")).equals("SUCCESS")) {
            JSONObject result = faceUtil.getSearchResult(res);

            if (Double.valueOf(result.getString("score")).intValue() >= 80) {
                Users user = usersMapper.login(result.getString("user_id"));
                if (user == null) {
                    throw new UsernameNotFoundException("用户名不存在！");
                }

                // 更新人脸
                // faceUtil.updateFace(base64, "csi_home", user.getUsername());

                List<GrantedAuthority> userRole = new ArrayList<>();

                if (user.getStatus() == 1) {
                    userRole = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_admin");
                } else if (user.getStatus() == 2) {
                    userRole = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_user");
                }

                JwtUser userDetails = new JwtUser(user, userRole);

                Employee employee = employeeService.getOne(new QueryWrapper<Employee>().select("id").eq("user_id", userDetails.getId()));
                // 回调信息
                Map<String, Object> data = new HashMap<>();
                data.put("employeeId", employee.getId());
                data.put("username", userDetails.getUsername());
                data.put("roleList", userDetails.getAuthorities());
                // 将权限集合转成String
                StringBuilder auth = new StringBuilder();
                userDetails.getAuthorities().forEach(item -> {
                    auth.append(item);
                    auth.append(",");
                });
                // 用户本次登录的token令牌
                data.put("token", "Bearer " + jwtTokenUtil.generateToken(userDetails.getId(), userDetails.getUsername(), auth.toString()));

                httpServletResponse.setContentType("application/json;charset=UTF-8");
                httpServletResponse.getWriter().write("{\"code\":200,\"msg\":\"success\",\"obj\":" + new ObjectMapper().writeValueAsString(data) + "}");

            } else {
                httpServletResponse.setContentType("application/json;charset=UTF-8");
                httpServletResponse.getWriter().write("{\"code\":200,\"msg\":\"failure\",\"obj\":\"人脸相似度偏低\"}");
            }
        } else {
            httpServletResponse.setContentType("application/json;charset=UTF-8");
            httpServletResponse.getWriter().write("{\"code\":200,\"msg\":\"failure\",\"obj\":\"人脸比对失败\"}");
        }
    }


    @PostMapping("/addFace")
    public String addFace(@RequestBody String str) {
        JSONObject jsonObject = JSONObject.parseObject(str);
        String username = jsonObject.getString("username");
        String image = jsonObject.getString("image");
        String res = faceUtil.addFace(image, "csi_home", username);
        if ("SUCCESS".equals(JSONObject.parseObject(res).getString("error_msg"))) {
            return "采集成功";
        } else {
            return "采集失败";
        }
    }

    @PostMapping("/deleteFace")
    public String deleteFace(@RequestBody String str) {
        JSONObject jsonObject = JSONObject.parseObject(str);
        String username = jsonObject.getString("username");
        String res = faceUtil.deleteFace("csi_home", username);
        if ("SUCCESS".equals(JSONObject.parseObject(res).getString("error_msg"))) {
            return "删除成功";
        } else {
            return "删除失败";
        }
    }

    @PostMapping("/updateFace")
    public String updateFace(@RequestBody String str) {
        JSONObject jsonObject = JSONObject.parseObject(str);
        String username = jsonObject.getString("username");
        String image = jsonObject.getString("image");
        String res = faceUtil.updateFace(image, "csi_home", username);
        if ("SUCCESS".equals(JSONObject.parseObject(res).getString("error_msg"))) {
            return "更新成功";
        } else {
            return "更新失败";
        }
    }

    @GetMapping("/queryAll")
    public List<Users> queryAll() {
        return usersMapper.selectList(null);
    }

    @PostMapping("/queryByUsername")
    public Users queryByUsername(@RequestBody String str) {
        JSONObject jsonObject = JSONObject.parseObject(str);
        String username = jsonObject.getString("username");
        return usersMapper.selectOne(new QueryWrapper<Users>().eq("username", username));
    }

    /**
     * 查询所有管理员
     */
    @GetMapping("/queryAll1")
    public List<Users> queryAll1() {
        return usersMapper.selectList(new QueryWrapper<Users>().eq("status", 1));
    }

    /**
     * 查询所有员工
     */
    @GetMapping("/queryAll2")
    public List<Users> queryAll2() {
        return usersMapper.selectList(new QueryWrapper<Users>().eq("status", 2));
    }

    @PostMapping("/insert")
    public Users insert(@RequestBody Users user) {
        Users user1 = new Users();
        user1.setUsername(user.getUsername());
        user1.setPassword(myPasswordEncoder.encode(user.getPassword()));
        user1.setStatus(user.getStatus());
        usersMapper.insert(user1);
        return user1;
    }

    @GetMapping("/deleteById/{id}")
    public Boolean deleteById(@PathVariable Integer id) {
        return usersMapper.deleteById(id) == 1;
    }

    /**
     * 员工更新密码
     */
    @PostMapping("/update")
    public Boolean update(@RequestBody String str, @AuthenticationPrincipal JwtUser jwtUser) {
        String password = JSONObject.parseObject(str).getString("password");
        Users user = new Users();
        user.setId(jwtUser.getId());
        user.setPassword(myPasswordEncoder.encode(password));
        return usersMapper.updateById(user) == 1;
    }

    /**
     * 管理员修改user表信息
     */
    @PostMapping("/admin-update")
    public Boolean update2(@RequestBody Users users) {
        return usersMapper.updateById(users) == 1;
    }

    /**
     * 查询用户名是否存在
     */
    @PostMapping("/queryExist")
    public Boolean queryExist(@RequestBody String str) {
        String username = JSONObject.parseObject(str).getString("username");
        return usersMapper.queryExist(username) != null;
    }

}
